//
//  AppDelegate.m
//  HeadYang
//
//  Created by sunmingming on 15/6/30.
//  Copyright (c) 2015年 xiaoluoli. All rights reserved.
//

#import "AppDelegate.h"
#import "LoginViewController.h"
#import "SMMNavigationController.h"
#import "MainTabViewController.h"
#import "AFNetworkActivityIndicatorManager.h"
#import "Pingpp.h"

@interface AppDelegate ()<CLLocationManagerDelegate>

@property(nonatomic,strong) LoginViewController *loginVC;
@property(nonatomic,strong) SMMNavigationController *loginNav;
@property(nonatomic,strong) MainTabViewController *mainTabVC;
@property(nonatomic,assign) int hasLocated;

-(void) locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations;
-(void) locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error;

@end

@implementation AppDelegate

@synthesize gps;

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    [AVOSCloud setApplicationId:@"lzjdqv3dajojgtnbovjp9v2ih4wh3moozb9sd19w5e3lqgnk" clientKey:@"xdeo0fn0cz474giyrdr51d05pb3erhvtakc6wau5cr6n9slt"];
    [AVAnalytics trackAppOpenedWithLaunchOptions:launchOptions];
    self.globalDBManager = [LKDBHelper getUsingLKDBHelper];//清空数据库
    self.myUserItem = [SpUserItem searchSingleWithWhere:nil orderBy:nil];
    if(!self.myUserItem)
    {
        self.myUserItem = [[SpUserItem alloc] init];
        [self.myUserItem saveToDB];
    }
    //userinfo:qsmn1vb952nqv5jcv8au9av6mke75shb
    NSLog(@"userinfo:   %@",self.myUserItem.token);
    
    self.goodsDic = nil;
    self.selectDate = [NSDate date];
    self.hasLocated = 0;
    self.gps = [CLLocationManager new];
    //定位修改（兼容性）
    if([[[UIDevice currentDevice] systemVersion] doubleValue]>8.0)
    {
        //设置定位权限 仅ios8有意义
        [self.gps requestWhenInUseAuthorization];//前台定位
    }
    if([CLLocationManager locationServicesEnabled]){
        NSLog(@"initing gps...");
        // 接收事件的实例
        gps.delegate = self;
        // 发生事件的的最小距离间隔（缺省是不指定）
        gps.distanceFilter = kCLDistanceFilterNone;
        // 精度 (缺省是Best)
        gps.desiredAccuracy = kCLLocationAccuracyBest;
        // 开始测量
        [gps startUpdatingLocation];
    }
    else{
        NSLog(@"gps init error");
        [SVProgressHUD showErrorWithStatus:@"获取GPS失败，请检查手机设置"];
    }
    
    self.allKGModal =[KGModal sharedInstance];
    [self.allKGModal setTapOutsideToDismiss:YES];
    [self.allKGModal setShowCloseButton:NO];
    [self.allKGModal setModalBackgroundColor:[UIColor clearColor]];
    
    self.loginVC = [LoginViewController new];
    self.loginNav = [[SMMNavigationController alloc] initWithRootViewController:self.loginVC];
    // Override point for customization after application launch.
    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];
    
    self.mainTabVC = [[MainTabViewController alloc] init];
    SMMNavigationController *nav = [[SMMNavigationController alloc] initWithRootViewController:self.mainTabVC];
    self.window.rootViewController = nav;
    
    AVQuery *query = [AVQuery queryWithClassName:@"HTMLURL"];
    query.limit = 1;
    AVObject *post = [query getObjectWithId:@"563360c600b0387b2d06c212"];
        NSLog(@"avos:  %@",[post valueForKey:@"Text"]);
    self.globalUrl = [post valueForKey:@"Text"];
#if 0
    if(!(self.myUserItem.username.length && self.myUserItem.password.length))
#endif
    {
        [self showLoginWindow];
    }
    return YES;
}

-(void)refreshRightBar{
    [self.mainTabVC refreshRightBar];
}

- (void)applicationWillResignActive:(UIApplication *)application {
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
}

- (void)applicationWillTerminate:(UIApplication *)application {
    [self.gps stopUpdatingLocation];
}

-(void)dismissLoginWindow
{
    [self.window.rootViewController dismissViewControllerAnimated:YES completion:nil];
}

-(void)showLoginWindow
{
    [self.window.rootViewController presentViewController:self.loginNav animated:NO completion:nil];
}

-(void)locationManager:(CLLocationManager *)manager
    didUpdateLocations:(NSArray *)locations{
    //    NSLog(@"get %i",[locations count]);
    if(![locations count])
        return;
    self.location = [locations firstObject];
    /*
     // 取得经纬度
     CLLocationCoordinate2D coordinate = self.location.coordinate;
     CLLocationDegrees latitude = coordinate.latitude;
     CLLocationDegrees longitude = coordinate.longitude;
     // 取得精度
     CLLocationAccuracy horizontal = self.location.horizontalAccuracy;
     CLLocationAccuracy vertical = self.location.verticalAccuracy;
     // 取得高度
     CLLocationDistance altitude = self.location.altitude;
     // 取得时刻
     NSDate *timestamp = [self.location timestamp];
     */
    // 以下面的格式输出 format: <latitude>, <longitude>> +/- <accuracy>m @ <date-time>
    //    NSLog(@"%@",[self.location description]);
}

-(void)locationManager:(CLLocationManager *)manager
      didFailWithError:(NSError *)error{
    [SVProgressHUD showErrorWithStatus:@"启动GPS失败，请检查手机设置"];
    NSLog(@"%@",[error localizedDescription]);
    //test
    float latitude = 32.061;
    float longitude = 118.79125;
    self.location = [[CLLocation alloc] initWithLatitude:latitude longitude:longitude];
}

- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
    [Pingpp handleOpenURL:url withCompletion:^(NSString *result, PingppError *error) {
        NSLog(@"appall result:%@",result);
        // result : success, fail, cancel, invalid
        if (error == nil) {
            if([result isEqualToString:@"success"]){
                [self.ddVC showAlertOfSuccess];
            }else if([result isEqualToString:@"fail"]){
                [SVProgressHUD showErrorWithStatus:@"付款失败"];
            }else if([result isEqualToString:@"cancel"]){
                [SVProgressHUD showErrorWithStatus:@"用户取消付款"];
            }else if([result isEqualToString:@"invalid"]){
            }
        } else {
            [SVProgressHUD showErrorWithStatus:[NSString stringWithFormat:@"result=%@ PingppError: code=%lu msg=%@", result, (unsigned long)error.code, [error getMsg]]];
        }
    }];
    return  YES;
}

@end
